/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.widget;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.model.enums.TransportType;
import lt.marsrutai.mobile.android.util.UnitConversionUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ScheduleNumber {

    private static final Logger logger = LoggerFactory.getLogger("ScheduleNumber");

    private static final int MAX_IMAGE_SIZE_DP = 48;
    private static final int MARGIN_RIGHT = 2;

    Activity activity;
    String number;
    TransportType transportType;
    String transportId;
    String scope;

    public ScheduleNumber(Activity activity) {
        this.activity = activity;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public void setTransportType(TransportType transportType) {
        this.transportType = transportType;
    }

    public void setScope(String scope) {
        this.scope = scope;
    }

    public void setTransportId(String transportId) {
        this.transportId = transportId;
    }

    public View getView() {
        if (TransportType.WALK.equals(transportType)) {
            ImageView scheduleNumber = (ImageView) activity.getLayoutInflater().inflate(R.layout.schedule_number_image, null);
            scaleImage(scheduleNumber);
            return scheduleNumber;
        }
        else {
            TextView scheduleNumber = (TextView) activity.getLayoutInflater().inflate(R.layout.schedule_number, null);

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.FILL_PARENT);
            layoutParams.setMargins(0, 0, MARGIN_RIGHT, 0);
            scheduleNumber.setLayoutParams(layoutParams);

            scheduleNumber.setText(number);
            scheduleNumber.setBackgroundColor(AppContext.getTransportInfoResolver().resolveTransportColor(scope, transportId));

            return scheduleNumber;
        }
    }

    /**
     * Courtesy of Jarno Argillander
     * http://stackoverflow.com/a/8233084/77102
     *
     * @param view
     */
    private void scaleImage(ImageView view)
    {
        // Get the ImageView and its bitmap
        Drawable drawing = view.getDrawable();
        Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();

        // Get current dimensions AND the desired bounding box
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int bounding = UnitConversionUtils.dpToPx(activity, MAX_IMAGE_SIZE_DP);
        logger.debug("original width = " + Integer.toString(width));
        logger.debug("original height = " + Integer.toString(height));
        logger.debug("bounding = " + Integer.toString(bounding));

        // Determine how much to scale: the dimension requiring less scaling is
        // closer to the its side. This way the image always stays inside your
        // bounding box AND either x/y axis touches it.
        float xScale = ((float) bounding) / width;
        float yScale = ((float) bounding) / height;
        float scale = (xScale <= yScale) ? xScale : yScale;
        logger.debug("xScale = " + Float.toString(xScale));
        logger.debug("yScale = " + Float.toString(yScale));
        logger.debug("scale = " + Float.toString(scale));

        // Create a matrix for the scaling and add the scaling data
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);

        // Create a new bitmap and convert it to a format understood by the ImageView
        Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        width = scaledBitmap.getWidth(); // re-use
        height = scaledBitmap.getHeight(); // re-use
        BitmapDrawable result = new BitmapDrawable(scaledBitmap);
        logger.debug("scaled width = " + Integer.toString(width));
        logger.debug("scaled height = " + Integer.toString(height));

        // Apply the scaled bitmap
        view.setImageDrawable(result);

        // Now change ImageView's dimensions to match the scaled image
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.width = width;
        params.height = height;
        view.setLayoutParams(params);
    }

}
